from typing import List

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession

from app import crud, models, schemas
from app.db.session import get_db

router = APIRouter()

@router.post("/", response_model=schemas.Item)
async def create_item(
    *, 
    db: AsyncSession = Depends(get_db), 
    item_in: schemas.ItemCreate
) -> models.Item:
    """
    Create new item.
    """
    return await crud.item.create(db=db, obj_in=item_in)

@router.get("/", response_model=List[schemas.Item])
async def read_items(
    db: AsyncSession = Depends(get_db),
    skip: int = 0,
    limit: int = 100,
) -> List[models.Item]:
    """
    Retrieve items.
    """
    return await crud.item.get_multi(db, skip=skip, limit=limit)

@router.get("/{id}", response_model=schemas.Item)
async def read_item(
    *, 
    db: AsyncSession = Depends(get_db), 
    id: int
) -> models.Item:
    """
    Get item by ID.
    """
    item = await crud.item.get(db=db, id=id)
    if not item:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

@router.put("/{id}", response_model=schemas.Item)
async def update_item(
    *, 
    db: AsyncSession = Depends(get_db), 
    id: int, 
    item_in: schemas.ItemUpdate
) -> models.Item:
    """
    Update an item.
    """
    item = await crud.item.get(db=db, id=id)
    if not item:
        raise HTTPException(status_code=404, detail="Item not found")
    return await crud.item.update(db=db, db_obj=item, obj_in=item_in)

@router.delete("/{id}", response_model=schemas.Item)
async def delete_item(
    *, 
    db: AsyncSession = Depends(get_db), 
    id: int
) -> models.Item:
    """
    Delete an item.
    """
    item = await crud.item.get(db=db, id=id)
    if not item:
        raise HTTPException(status_code=404, detail="Item not found")
    return await crud.item.remove(db=db, id=id)
